package service

import (
	"encoding/json"
	"errors"
	"fmt"
	"git.inedcn.com/ined/cmn"
	"math"
	"rongyy/src/helper"
	"rongyy/src/middlewares"
	"rongyy/src/models"
	"time"
)

type PopularizationService struct {
}

/*
*
用于pc端
*/
func (ps *PopularizationService) GetListAndUpdate() error {
	wx := &WxConfService{}
	token, _ := wx.GetGzhToken()
	print(token)
	//

	type reqModel struct {
		NoContent int `json:"no_content"`
		Count     int `json:"count"`
		Offset    int `json:"offset"`
	}
	// 第一步 获取文章总数
	req := &reqModel{
		NoContent: 1,
		Count:     1,
		Offset:    0,
	}
	result, err := helper.PostJson("https://api.weixin.qq.com/cgi-bin/freepublish/batchget?access_token="+token, req)
	if err != nil {
		return err
	}

	rr1 := &models.WxListModel{}
	err = json.Unmarshal(result, rr1)

	count := 2  // 一次拉取的数据
	offset := 0 // 初始值
	total := math.Ceil(float64(rr1.TotalCount) / float64(count))
	var x int
	var i int
	var j int

	for x = 0; x < int(total); x++ {
		reqa := &reqModel{
			NoContent: 1,
			Count:     count,
			Offset:    offset,
		}
		result, _ = helper.PostJson("https://api.weixin.qq.com/cgi-bin/freepublish/batchget?access_token="+token, reqa)
		rr2 := &models.WxListModel{}
		i = 0
		j = 0
		err = json.Unmarshal(result, rr2)
		if rr2.ItemCount > 0 {
			for i = 0; i < rr2.ItemCount; i++ {
				for j = 0; j < len(rr2.Item[i].Content.NewsItem); j++ {
					pm := &models.PopularizationArticle{}
					pm.ArticleId = rr2.Item[i].ArticleId
					ni := rr2.Item[i].Content.NewsItem[j]
					pm.Title = ni.Title
					pm.Author = ni.Author
					pm.Digest = ni.Digest
					pm.Url = ni.Url
					pm.ContentSourceUrl = ni.ContentSourceUrl
					pm.ThumbMediaId = ni.ThumbMediaId
					tm := time.Unix(rr2.Item[i].UpdateTime, 0)
					pm.UpdatedAtWx = cmn.JsonTime(tm)
					err = pm.InsertOrUpdate(pm)
				}
			}
			offset = offset + count
		}
	}
	return nil
}

func (ps *PopularizationService) GetDetail(id string) (*models.PopularizationArticle, error) {
	wx := &WxConfService{}
	pm := &models.PopularizationArticle{}
	token, _ := wx.GetToken()
	print(token)
	//
	type reqModel struct {
		MediaId string `json:"media_id"`
	}
	req := &reqModel{
		MediaId: id,
	}
	result, err := helper.PostJson("https://api.weixin.qq.com/cgi-bin/material/get_material?access_token="+token, req)
	if err != nil {
		return nil, err
	}

	pm, _, err = pm.FindByMediaId(id)
	if err != nil {
		return nil, err
	}

	rr := &models.NewsItem{}
	err = json.Unmarshal(result, rr)

	pm.Title = rr.NewsItem[0].Title
	pm.Author = rr.NewsItem[0].Author
	pm.Digest = rr.NewsItem[0].Digest
	pm.Content = rr.NewsItem[0].Content
	return pm, nil
}

func (ps *PopularizationService) Query(req *models.ReqPopularizationArticleFilter) ([]models.PopularizationArticleTag, int64, error) {
	mzm := models.PopularizationArticle{}
	return mzm.Query(*req)
}

func (ps *PopularizationService) QueryPc(req *models.ReqPopularizationArticleFilter) ([]models.PopularizationArticleTag, int64, error) {
	mzm := models.PopularizationArticle{}
	return mzm.QueryPc(*req)
}

func (ds *PopularizationService) InsertOrUpdate(req *models.PopularizationArticle) (*models.PopularizationArticle, error) {
	pa := &models.PopularizationArticle{}
	u, has, err := pa.FindByMediaId(req.Url)
	if err != nil {
		return nil, err
	}
	if !has {
		u, err = pa.Insert()
		if err != nil {
			return nil, err
		}
	} else {
		u, err = pa.Update(u.Id)
		if err != nil {
			return nil, err
		}
	}

	return u, nil
}

func (ds *PopularizationService) TagInsert(req *models.PopularizationTag) error {
	pa := &models.PopularizationArticle{}
	has, err := pa.FindTagByName(req.Name)
	if err != nil {
		return err
	}
	if !has {
		err = pa.InsertTag(req)
		if err != nil {
			return err
		}
	}
	return nil
}

func (ds *PopularizationService) TagUpdate(req *models.PopularizationTag) error {
	pa := &models.PopularizationArticle{}
	_, has, err := pa.FindTagById(req.Id)
	if err != nil {
		return err
	}

	if has {
		err := pa.UpdateTag(req)
		if err != nil {
			return err
		}
	} else {
		return errors.New("标签ID错误或不存在")
	}

	return nil
}

func (ds *PopularizationService) ArticleUpdateTag(req *models.PopularizationArticle) error {
	pa := &models.PopularizationArticle{}
	_, has, err := pa.FindByMediaId(req.Url)
	if err != nil {
		return err
	}

	if has {
		_, err := pa.ArticleUpdateTag(req.Id, req.Tag)
		if err != nil {
			return err
		}
	} else {
		return errors.New("文章不存在")
	}

	return nil
}

func (ds *PopularizationService) ArticleUpdate(req *models.PopularizationArticle) error {
	pa := &models.PopularizationArticle{}
	if req.Author != "" {
		pa.Author = req.Author
	}

	if req.Title != "" {
		pa.Title = req.Title
	}

	_, has, err := pa.FindByMediaId(req.Url)
	if err != nil {
		return err
	}

	if has {
		_, err := pa.Update(req.Id)
		if err != nil {
			return err
		}
	} else {
		return errors.New("文章不存在")
	}
	return nil
}

func (ds *PopularizationService) TagQuery() ([]models.PopularizationTag, int64, error) {
	pa := &models.PopularizationArticle{}
	data, total, err := pa.QueryTag()
	if err != nil {
		return nil, 0, err
	}

	return data, total, nil
}

func (uc *PopularizationService) AddSwiper(pa *models.PopularizationSwiper) error {
	pp := &models.PopularizationArticle{}
	err := pp.InsertSwiper(pa)
	if err != nil {
		middlewares.Logger.Println("ERROR - AddSwiper failed ", err)
	}
	return nil
}

func (ds *PopularizationService) AddLike(req *models.PopularizationRecord) error {
	pa := &models.PopularizationArticle{}
	err := pa.AddLike(req)
	if err != nil {
		return err
	}
	return nil
}

func (uc *PopularizationService) SwiperList() ([]models.PopularizationSwiper, int64, error) {
	pp := &models.PopularizationArticle{}
	data, total, err := pp.SwiperList()
	if err != nil {
		middlewares.Logger.Println("ERROR - AddSwiper failed ", err)
		return nil, 0, err
	}
	return data, total, nil
}

func (uc *PopularizationService) DeleteSwiper(id int64) error {
	pp := &models.PopularizationArticle{}
	err := pp.DeleteSwiper(id)
	if err != nil {
		middlewares.Logger.Println("ERROR - AddSwiper failed ", err)
		return err
	}
	return nil
}

func (ds *PopularizationService) AddRecord(req *models.PopularizationRecord) error {
	pa := &models.PopularizationArticle{}
	err := pa.AddRecord(req)
	if err != nil {
		return err
	}
	return nil
}

func (ds *PopularizationService) TagTopList() ([]models.TagTopList, error) {
	pa := &models.PopularizationArticle{}
	data, err := pa.TagTopList()
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (ps *PopularizationService) GetThumb(id string) ([]byte, error) {
	type reqThumb struct {
		MediaId string `json:"media_id"`
	}
	wx := &WxConfService{}
	token, _ := wx.GetGzhToken()
	reqT := reqThumb{
		MediaId: id,
	}
	data, err := helper.PostJson("https://api.weixin.qq.com/cgi-bin/material/get_material?access_token="+token, reqT)
	fmt.Println(data)
	if err != nil {
		return nil, err
	}

	return data, nil
}

func (ps *PopularizationService) Insert(req *models.PopularizationArticle) (*models.PopularizationArticle, error) {
	data, err := req.Insert()
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (ps *PopularizationService) StatisRead(req *models.ReqPopularizationArticleFilter) ([]models.StatisReads, error) {
	pa := &models.PopularizationArticle{}
	data, err := pa.StatisRead(req)
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (ds *PopularizationService) UpdateThumbImg(req *models.PopularizationArticle) error {
	pa := &models.PopularizationArticle{}
	err := pa.UpdateThumbImg(req)
	if err != nil {
		return err
	}
	return nil
}

func (ds *PopularizationService) Link(id int64) error {
	pa := &models.PopularizationArticle{}
	err := pa.Link(id)
	if err != nil {
		return err
	}
	return nil
}

func (ds *PopularizationService) UnLink(id int64) error {
	pa := &models.PopularizationArticle{}
	err := pa.UnLink(id)
	if err != nil {
		return err
	}
	return nil
}

func (ds *PopularizationService) Delete(id int64) error {
	pa := &models.PopularizationArticle{}
	err := pa.Delete(id)
	if err != nil {
		return err
	}
	return nil
}

func (ds *PopularizationService) FindByKeyName(req *models.ReqPopularizationArticleFilter) ([]models.PopularizationArticle, int64, error) {
	data, total, err := (&models.PopularizationArticle{}).FindByKeyName(req)
	if err != nil {
		return nil, 0, err
	}
	return data, total, err
}
